//
//  DeploySDK.m
//  latheDataTrack
//
//  Created by Kang on 16/7/6.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "DeploySDK.h"

@implementation DeploySDK

//???:这是邪恶的分割线！ --------------------------------------------PushSDK---------------------------------*/
//TODO: 推送的汇总
- (void)registerPushServiceWithApplication:(nonnull UIApplication *)app :(nonnull NSDictionary *)launch {
    [self registerAPNS:app withDictionary:launch];
    
    
    //ALBBSDK
    [self initALBBSDKWithOptions];
    [self listenerOnChannelOpened]; //监听通道
    [self registerMsgReceive]; //收到的推送消息
}

#pragma mark -  推送的业务逻辑处理、判断方法
- (void)callMethodPuchApplication:(nonnull UIApplication*)application receiveRemoteNot:(nonnull NSDictionary*)userInfo enclosureInfo:(void (^ _Nullable)(id _Nullable))info  {
    
    /*  NSString *alertStr = [[userInfo objectForKey:@"aps"] objectForKey:@"alert"]; //推送的正文
     NSString *badgeStr = [userInfo objectForKey:@"badge"];  // 信息条数
     NSLog(@"推送条数--->%@",badgeStr);
     [application setApplicationIconBadgeNumber:[badgeStr integerValue]];
     [[NSUserDefaults standardUserDefaults] setObject:badgeStr forKey:USER_INFO_Defaults];
     
     NSLog(@"%@--->%@",alertStr,badgeStr);
     // 前台 或者 后台开启
     NSLog(@"%ld",(long)[UIApplication sharedApplication].applicationState);
     if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive || application.applicationState == UIApplicationStateBackground) {
     
     // isJudge = YES;
     //建立本地推送
     //        UILocalNotification *localNotification = [[UILocalNotification alloc] init];
     //        localNotification.userInfo = userInfo;
     //        localNotification.soundName = UILocalNotificationDefaultSoundName;//@"SStext.wav"; //
     //        localNotification.alertBody = userInfo[@"aps"][@"alert"];
     //        localNotification.fireDate = [NSDate date];
     //        [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
     
     }else { // 杀死状态--直接跳转 - 不是通知栏
     
     //        TabBarC *tabbarCont = (TabBarC *)self.window.rootViewController;
     //        NavigationC *navigationCont = (NavigationC *)tabbarCont.viewControllers[0];
     //        if(navigationCont.viewControllers.count > 1) {
     //            [navigationCont popToRootViewControllerAnimated:YES];
     //        }
     //
     //        if (![navigationCont.tabBarController.selectedViewController isEqual:navigationCont]) {
     //            navigationCont.tabBarController.selectedIndex = 0;
     //        }
     //
     //        NSLog(@"%@--->%@",navigationCont.viewControllers,userInfo);
     //        SearchVC * search = navigationCont.viewControllers[0];
     //        [search JumpWithVlue:userInfo];
     } */
    
    //[application setApplicationIconBadgeNumber:0]; 不清零
    //  [BPush handleNotification:userInfo]; //用来给百度推送做统计的
}

#pragma mark - 注册推送
- (void)registerAPNS:(UIApplication *)application withDictionary:(NSDictionary *)launchOptions {
    if (IOS_VERSION >= 8.0) {
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [application registerForRemoteNotifications];
    }else {
        UIRemoteNotificationType myTypes =(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound);
        [application registerForRemoteNotificationTypes:myTypes];
    }
    
    [CloudPushSDK handleLaunching:launchOptions]; // 作为 apns 消息统计
    
    [[UIApplication sharedApplication] cancelAllLocalNotifications]; // 清除全部通知。
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; //角标清0
}

#pragma mark - 初始化阿里百川推送
- (void)initALBBSDKWithOptions {
#if DEBUG
    [[ALBBSDK sharedInstance] setDebugLogOpen:NO];//开发阶段打开日志开关，方便排查错误信息
#endif
    [[ALBBSDK sharedInstance] asyncInit:^{
        NSLog(@"======================> 初始化成功");
        NSLog(@"======================> DeviceID：%@", [CloudPushSDK getDeviceId]);
        NSLog(@"======================> getVersion：%@", [CloudPushSDK getVersion]);
    }failure:^(NSError *error) {
        NSLog(@"======================> 初始化失败:%@",error);
    }];
    
}

#pragma mark - 注册通道监听
- (void)listenerOnChannelOpened {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onChannelOpened:) name:@"CCPDidChannelConnectedSuccess" object:nil]; // 注册
}
- (void) registerMsgReceive {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageReceived:) name:@"CCPDidReceiveMessageNotification" object:nil]; // 注册
}

#pragma mark - 推送下来的消息抵达的处理示例
- (void)onChannelOpened:(NSNotification *)notification {
    NSLog(@"消息通道建立成功");
}

- (void)onMessageReceived:(NSNotification *)notification {
    
    // 推送过来的信息，不包含字段，是否怎么设置呢？
    NSData *data = [notification object];
    NSString *message = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    //    LZLPushMessage *tempVO = [[LZLPushMessage alloc] init];
    //    tempVO.messageContent = message;
    //    tempVO.isRead = 0;
    
    // 报警提示
    if(![NSThread isMainThread])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            //   NSNotification* notif = [NSNotification notificationWithName:BADGE_Num object:self userInfo:[notification userInfo]];
            //      [[NSNotificationCenter defaultCenter] postNotification:notif];
            
            if(message != nil) {
                // [self insertPushMessage:tempVO];
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"有消息抵达，下拉更新"
                                                                message:message
                                                               delegate:self
                                                      cancelButtonTitle:@"取消"
                                                      otherButtonTitles:@"确定",nil];
                [alert show];
            }
        });
    } else {
        if(message != nil) {
            //[self insertPushMessage:tempVO];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"有消息抵达，下拉更新"
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"取消"
                                                  otherButtonTitles:@"确定",nil];
            [alert show];
        }
    }
}

#pragma mark - 统计回调
//+  (void)receiveRemoteNotification:(nonnull NSDictionary *)user {
//    [CloudPushSDK handleReceiveRemoteNotification:user];
//}

#pragma mark - 设置 访问密匙 对取出的cookie进行反归档处理
- (void)updateSession{
    NSArray *cookies =[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"allCookie"]];
    if (cookies){
        NSHTTPCookieStorage *cookieStorage= [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (id cookie in cookies ){
            [cookieStorage setCookie:(NSHTTPCookie *)cookie]; //把保存在本地的Cookie 设置进去
            NSLog(@"比较后-AppDelegate这打印：--->%@",[(NSHTTPCookie *)cookie valueForKey:@"value"]);
        }
    }
}


//???:这是邪恶的分割线！ ------------------------------------------SMSSDK-----------------------------------*/


@end
